package com.yunchang.springboot.scheduled.mwsfinance;

import com.yunchang.springboot.base.BaseService;
import com.yunchang.springboot.mapper.mws.finances.MwsFinancesFinancialReportMapper;
import com.yunchang.springboot.mapper.mwsutils.CwfzFinancialSubjectsMapper;
import com.yunchang.springboot.mapper.mwsutils.CwfzMarketplaceCountryMapper;
import com.yunchang.springboot.models.mwsfinance.FPaymentOtherFees;
import com.yunchang.springboot.models.mwsfinance.MwsFinancesFinancialReport;
import com.yunchang.springboot.utils.DateUtil;
import com.yunchang.springboot.utils.UUIDUtil;
import com.yunchang.springboot.utils.mwsutils.GetCountryByCurrency;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * payment其他费用
 * @author Administrator
 */
@Component
@Configuration
@Service
@Slf4j
@EnableScheduling
public class FPaymentOtherFeesScheduled extends BaseService {

    static final String FORM = "Payment";

    static final String TRANSACTION_TYPE = "other";

    static final String TYPE = "Otherdefault";

    static final String COUNTRY_CODE = "GB";

    static final String COUNTRY_CODE_UK = "UK";

    static String DOCUMENTS_ID = "QTFYD";

    /**
     * 用于查询countryName的类
     */
    private CwfzMarketplaceCountryMapper cwfzMarketplaceCountryMapper;

    @Autowired
    public void setCwfzMarketplaceCountryMapper(CwfzMarketplaceCountryMapper cwfzMarketplaceCountryMapper) {
        this.cwfzMarketplaceCountryMapper = cwfzMarketplaceCountryMapper;
    }

    /**
     * 借贷关系
     */
    private CwfzFinancialSubjectsMapper cwfzFinancialSubjectsMapper;

    @Autowired
    public void setCwfzFinancialSubjectsMapper(CwfzFinancialSubjectsMapper cwfzFinancialSubjectsMapper) {
        this.cwfzFinancialSubjectsMapper = cwfzFinancialSubjectsMapper;
    }

    /**
     * finance原始数据
     */
    private MwsFinancesFinancialReportMapper mwsFinancesFinancialReportMapper;

    @Autowired
    public void setMwsFinancesFinancialReportMapper(MwsFinancesFinancialReportMapper mwsFinancesFinancialReportMapper){
        this.mwsFinancesFinancialReportMapper = mwsFinancesFinancialReportMapper;
    }

    /**
     * 销售订单定时任务
     */
    private FPaymentSalesScheduled fPaymentSalesScheduled;

    @Autowired
    public void setFPaymentSalesScheduled(FPaymentSalesScheduled fPaymentSalesScheduled){
        this.fPaymentSalesScheduled = fPaymentSalesScheduled;
    }

//    @Scheduled(cron = "23 03 18 08 07 ?")
    @Transactional(rollbackFor = Exception.class)
    public void getFPaymentOtherFees() {
        List<MwsFinancesFinancialReport> mwsFinancesFinancialReportList = mwsFinancesFinancialReportMapper.selectByFinanceStatusAndTransactionTypeList(1, Arrays.asList("Refund","Order"));
        if (null != mwsFinancesFinancialReportList && !mwsFinancesFinancialReportList.isEmpty()) {
            List<Object> fPaymentOtherFeesList = new ArrayList<>(mwsFinancesFinancialReportList.size());
            for (MwsFinancesFinancialReport mwsFinancesFinancialReport : mwsFinancesFinancialReportList) {
                FPaymentOtherFees fPaymentOtherFees = new FPaymentOtherFees();
                fPaymentOtherFees.setIsManualAdjustment(1);
                fPaymentOtherFees.setApprovalStatus(1);
                fPaymentOtherFees.setCountryStatus(1);
                fPaymentOtherFees.setDocumentsId(DOCUMENTS_ID + UUIDUtil.getUUID());
                fPaymentOtherFees.setDate(mwsFinancesFinancialReport.getPostedDate());
                fPaymentOtherFees.setSellerId(mwsFinancesFinancialReport.getSellerId());
                String currency = mwsFinancesFinancialReport.getCurrency();
                fPaymentOtherFees.setCurrency(currency);
                String countryCode = mwsFinancesFinancialReport.getCountryCode();
                String financialEventGroupId = mwsFinancesFinancialReport.getFinancialEventGroupId();
                String marketplaceName = mwsFinancesFinancialReport.getMarketplaceName();
                Map<String,String> countryMap = getCountry(countryCode,currency,marketplaceName,financialEventGroupId);
                if(null != countryMap && countryMap.containsKey("country3")){
                    fPaymentOtherFees.setCountryStatus(2);
                }
                if(null != countryMap){
                    countryCode = countryMap.get("country");
                    if(!StringUtils.isEmpty(countryCode)){
                        if(countryCode.equals(COUNTRY_CODE)){
                            countryCode = COUNTRY_CODE_UK;
                        }
                    }
                    fPaymentOtherFees.setCountry(countryCode);
                }
                fPaymentOtherFees.setOrderId(mwsFinancesFinancialReport.getAmazonOrderId());
                fPaymentOtherFees.setSku(mwsFinancesFinancialReport.getSku());
                String amountDescription = mwsFinancesFinancialReport.getAmountDescription();
                String amountType = mwsFinancesFinancialReport.getAmountType();
                String transactionType = mwsFinancesFinancialReport.getTransactionType();
                String type = getType(amountDescription,amountType,transactionType);
                fPaymentOtherFees.setType(type);
                Double originalAmount = mwsFinancesFinancialReport.getAmount();
                fPaymentOtherFees.setOriginalAmount(originalAmount);
                fPaymentOtherFees.setAmount(Math.abs(originalAmount));
                Map<String,String> debitSubjectIdMap = getDebitSubjectId(originalAmount,type);
                if(null != debitSubjectIdMap && debitSubjectIdMap.containsKey("debitSubjectId2")){
                    fPaymentOtherFees.setIsManualAdjustment(2);
                    fPaymentOtherFees.setDebitSubjectId(debitSubjectIdMap.get("debitSubjectId2"));
                }else {
                    fPaymentOtherFees.setDebitSubjectId(debitSubjectIdMap.get("debitSubjectId"));
                }
                Map<String,String> creditSubjectIdMap = getCreditSubjectId(originalAmount,type);
                if(null != creditSubjectIdMap && creditSubjectIdMap.containsKey("creditSubjectId2")){
                    fPaymentOtherFees.setIsManualAdjustment(2);
                    fPaymentOtherFees.setCreditSubjectId(creditSubjectIdMap.get("creditSubjectId2"));
                }else{
                    fPaymentOtherFees.setCreditSubjectId(creditSubjectIdMap.get("creditSubjectId"));
                }
                fPaymentOtherFees.setCreateTime(DateUtil.getTodayDate("yyyy-MM-dd HH:mm:ss"));
                fPaymentOtherFees.setUpdateTime(DateUtil.getTodayDate("yyyy-MM-dd HH:mm:ss"));
                mwsFinancesFinancialReport.setFinanceStatus(2);
                fPaymentOtherFeesList.add(fPaymentOtherFees);
            }
            try {
                baseInsertList(fPaymentOtherFeesList);
                log.info("数据已插入，开始修改原始数据中的状态");
                mwsFinancesFinancialReportMapper.updateMwsFinancesFinancialReportList(mwsFinancesFinancialReportList);
                log.info("状态已修改，结束");
            } catch (Exception e) {
                log.error("插入数据时出现错误，payment其他费用" + e);
                throw new RuntimeException("插入数据时出现错误，payment其他费用");
            }
        } else {
            log.info("未查询到对应的payment其他费用数据列表，时间为" + DateUtil.getTodayDate("yyyy-MM-dd HH:mm:ss"));
        }
    }

    /**
     * 根据originalAmount和type获取debitSubjectId
     *
     * @param originalAmount
     * @param type
     * @return
     */
    public Map<String,String> getDebitSubjectId(Double originalAmount, String type) {
        String debitSubjectId;
        if (null != originalAmount) {
            if (originalAmount > 0) {
                debitSubjectId = cwfzFinancialSubjectsMapper.getDebitSubjectIdPositiveByTypeAndFormTransactionType(type, FORM, TRANSACTION_TYPE);
                if(StringUtils.isEmpty(debitSubjectId)){
                    type = TYPE;
                    debitSubjectId = cwfzFinancialSubjectsMapper.getDebitSubjectIdPositiveByTypeAndFormTransactionType(type, FORM, TRANSACTION_TYPE);
                    String finalDebitSubjectId1 = debitSubjectId;
                    return new HashMap<String,String>(1){{
                        put("debitSubjectId2", finalDebitSubjectId1);
                    }};
                }else {
                    String finalDebitSubjectId = debitSubjectId;
                    return new HashMap<String,String>(1){{
                        put("debitSubjectId", finalDebitSubjectId);
                    }};
                }
            } else if (originalAmount < 0) {
                debitSubjectId = cwfzFinancialSubjectsMapper.getDebitSubjectIdNegativeByTypeAndFormTransactionType(type, FORM, TRANSACTION_TYPE);
                if(StringUtils.isEmpty(debitSubjectId)){
                    type = TYPE;
                    debitSubjectId = cwfzFinancialSubjectsMapper.getDebitSubjectIdNegativeByTypeAndFormTransactionType(type, FORM, TRANSACTION_TYPE);
                    String finalDebitSubjectId1 = debitSubjectId;
                    return new HashMap<String,String>(1){{
                        put("debitSubjectId2", finalDebitSubjectId1);
                    }};
                }else {
                    String finalDebitSubjectId = debitSubjectId;
                    return new HashMap<String,String>(1){{
                        put("debitSubjectId", finalDebitSubjectId);
                    }};
                }
            } else {
                log.warn("根据originalAmount和type获取debitSubjectId,originalAmount等于0,payment其他费用");
            }
        } else {
            log.warn("根据originalAmount和type获取debitSubjectId,originalAmount为空,payment其他费用");
        }
        return null;
    }

    /**
     * 根据originalAmount和type获取creditSubjectId
     *
     * @param originalAmount
     * @param type
     * @return
     */
    public Map<String,String> getCreditSubjectId(Double originalAmount, String type) {
        String creditSubjectId;
        if (null != originalAmount) {
            if (originalAmount > 0) {
                creditSubjectId = cwfzFinancialSubjectsMapper.getCreditSubjectIdPositiveByTypeAndFormTransactionType(type, FORM, TRANSACTION_TYPE);
                if(StringUtils.isEmpty(creditSubjectId)){
                    type = TYPE;
                    creditSubjectId = cwfzFinancialSubjectsMapper.getCreditSubjectIdPositiveByTypeAndFormTransactionType(type, FORM, TRANSACTION_TYPE);
                    String finalCreditSubjectId = creditSubjectId;
                    return new HashMap<String,String>(1){{
                        put("creditSubjectId2", finalCreditSubjectId);
                    }};
                }else {
                    String finalCreditSubjectId1 = creditSubjectId;
                    return new HashMap<String,String>(1){{
                        put("creditSubjectId", finalCreditSubjectId1);
                    }};
                }
            } else if (originalAmount < 0) {
                creditSubjectId = cwfzFinancialSubjectsMapper.getCreditSubjectIdNegativeByTypeAndFormTransactionType(type, FORM, TRANSACTION_TYPE);
                if(StringUtils.isEmpty(creditSubjectId)){
                    type = TYPE;
                    creditSubjectId = cwfzFinancialSubjectsMapper.getCreditSubjectIdNegativeByTypeAndFormTransactionType(type, FORM, TRANSACTION_TYPE);
                    String finalCreditSubjectId = creditSubjectId;
                    return new HashMap<String,String>(1){{
                        put("creditSubjectId2", finalCreditSubjectId);
                    }};
                }else {
                    String finalCreditSubjectId1 = creditSubjectId;
                    return new HashMap<String,String>(1){{
                        put("creditSubjectId", finalCreditSubjectId1);
                    }};
                }
            } else {
                log.warn("根据originalAmount和type获取debitSubjectId,originalAmount为0,payment其他费用");
            }
        } else {
            log.warn("根据originalAmount和type获取debitSubjectId,originalAmount为空,payment其他费用");
        }
        return null;
    }

    /**
     * 获取country
     * @param countryCode
     * @param currency
     * @param marketplaceName
     * @param financialEventGroupId
     * @return
     */
    public Map<String,String> getCountry(String countryCode, String currency, String marketplaceName,String financialEventGroupId){
        String currencyValue = "EUR";
        String marketplaceNameValue = "Non-Amazon";
        if(StringUtils.isEmpty(countryCode)){
            if(currency.equals(currencyValue)){
                if(StringUtils.isEmpty(marketplaceName)){
                    String marketplaceNameByFinancial = mwsFinancesFinancialReportMapper.selectMarketplaceNameByFinancialEventGroupId(financialEventGroupId);
                    if(!StringUtils.isEmpty(marketplaceNameByFinancial)){
                     return  new HashMap<String,String>(1){{
                         put("country",cwfzMarketplaceCountryMapper.selectCountryByMarketplace(marketplaceNameByFinancial));
                     }};
                    }
                }else{
                    if(marketplaceName.equals(marketplaceNameValue)){
                        return new HashMap<String,String>(1){{
                            put("country3",null);
                        }};
                    }else {
                        return new HashMap<String,String>(1){{
                            put("country",cwfzMarketplaceCountryMapper.selectCountryByMarketplace(marketplaceName));
                        }};
                    }
                }
            }else {
                return new HashMap<String,String>(1){{
                    put("country", GetCountryByCurrency.getCountryByCurrency(currency));
                }};
            }
        }else {
            return new HashMap<String,String>(1){{
                put("country",countryCode);
            }};
        }
        log.info("获取country为空！根据finance生成payment其他费用！");
        return null;
    }

    /**
     * 获取type
     * @param amountDescription
     * @param amountType
     * @param transactionType
     * @return
     */
    public String getType(String amountDescription,String amountType,String transactionType){
        String amountDescriptionValue = "TransactionTotalAmount";
        if(!StringUtils.isEmpty(amountDescription) && !amountDescriptionValue.equals(amountDescription)){
            return amountDescription;
        }else {
            if(!StringUtils.isEmpty(amountType)){
                return amountType;
            }else {
                return transactionType;
            }
        }
    }


}
